<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>学生管理</span>
        </div>
      </template>

      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
        class="query-form"
      >
        <el-form-item label="学生姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入学生姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学号" prop="studentNumber">
          <el-input
            v-model="queryParams.studentNumber"
            placeholder="请输入学号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button
          type="primary"
          @click="handleCreate"
        >
          <el-icon><Plus /></el-icon>新增学生
        </el-button>
        <el-button @click="getList">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="studentList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="学生姓名" />
        <el-table-column prop="studentNumber" label="学号" />
        <el-table-column prop="gender" label="性别" />
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="className" label="班级" />
        <el-table-column prop="majorName" label="专业" />
        <el-table-column prop="departmentName" label="院系" />
        <el-table-column prop="contact" label="联系方式" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleUpdate(scope.row)"
            >
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改学生对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form ref="studentForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="studentNumber">
          <el-input v-model="form.studentNumber" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别" clearable>
            <el-option
              v-for="item in genderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="form.age" type="number" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" placeholder="请选择班级" clearable>
            <el-option
              v-for="item in classOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="majorId">
          <el-select v-model="form.majorId" placeholder="请选择专业" clearable>
            <el-option
              v-for="item in majorOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="院系" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择院系" clearable>
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  getStudentPage,
  getStudentById,
  saveOrUpdateStudent,
  deleteStudent
} from '@/api/student'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/date'
import { Plus, Edit, Refresh, Delete } from '@element-plus/icons-vue'

// 页面加载状态
const loading = ref(false)
// 总条数
const total = ref(0)
// 学生列表
const studentList = ref([])
// 弹窗状态
const open = ref(false)
// 弹窗标题
const dialogTitle = ref('')
// 班级选项
const classOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  studentNumber: ''
})

// 表单参数
const form = ref({})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }],
  studentNumber: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
  gender: [{ required: true, message: '性别不能为空', trigger: 'change' }],
  age: [{ required: true, message: '年龄不能为空', trigger: 'blur' }],
  classId: [{ required: true, message: '班级不能为空', trigger: 'change' }],
  majorId: [{ required: true, message: '专业不能为空', trigger: 'change' }],
  departmentId: [{ required: true, message: '院系不能为空', trigger: 'change' }],
  contact: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }]
}

// 性别选项
const genderOptions = ref([
  { value: '男', label: '男' },
  { value: '女', label: '女' }
])

// 专业选项
const majorOptions = ref([])

// 院系选项
const departmentOptions = ref([])

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getStudentPage(queryParams)
    studentList.value = res.records
    total.value = res.total
  } catch (error) {
    ElMessage.error('获取学生列表失败')
    console.error('Failed to get student list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.name = ''
  queryParams.studentNumber = ''
  queryParams.pageNum = 1
  getList()
}

// 新增按钮操作
const handleCreate = () => {
  dialogTitle.value = '添加学生'
  open.value = true
  form.value = {
    id: undefined,
    name: '',
    studentNumber: '',
    gender: '',
    age: '',
    classId: '',
    majorId: '',
    departmentId: '',
    contact: ''
  }
}

// 修改按钮操作
const handleUpdate = async (row) => {
  dialogTitle.value = '修改学生'
  open.value = true
  try {
    const res = await getStudentById(row.id)
    form.value = res
  } catch (error) {
    ElMessage.error('获取学生信息失败')
    console.error('Failed to get student info:', error)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await saveOrUpdateStudent(form.value)
    ElMessage.success(`${dialogTitle.value}成功`)
    open.value = false
    getList()
  } catch (error) {
    ElMessage.error(`${dialogTitle.value}失败`)
    console.error('Failed to save or update student:', error)
  }
}

// 取消按钮
const cancel = () => {
  open.value = false
  resetForm()
}

// 表单重置
const resetForm = () => {
  form.value = {
    id: undefined,
    name: '',
    studentNumber: '',
    gender: '',
    age: '',
    classId: '',
    majorId: '',
    departmentId: '',
    contact: ''
  }
  
  // 重置表单验证
  if (studentForm.value) {
    studentForm.value.resetFields()
  }
}

// 删除学生
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除学生"${row.name}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => deleteStudent(row.id))
    .then(() => {
      ElMessage.success('删除成功')
      getList()
    })
    .catch(() => {})
}

// 获取班级、专业、院系选项数据
const getOptionsData = async () => {
  // 这里需要调用相应的API获取选项数据
  // 暂时使用模拟数据
  classOptions.value = [
    { id: 1, name: '一班' },
    { id: 2, name: '二班' }
  ]
  
  majorOptions.value = [
    { id: 1, name: '计算机科学与技术' },
    { id: 2, name: '软件工程' }
  ]
  
  departmentOptions.value = [
    { id: 1, name: '计算机学院' },
    { id: 2, name: '软件学院' }
  ]
}

// 初始化
onMounted(() => {
  getList()
  getOptionsData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: -10px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>